#!/usr/bin/env python

# ------------------------------------------------------------
# ::                        WIGA-SOFT                       ::
# ------------------------------------------------------------
# views.py
# Controllers layer
# Created by: Vycas
# Version: 1.0
# ------------------------------------------------------------

from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from loader import DataLoader
from models import Task
from charts.charts import intensityChart, budgetChart, loadChart
from pao.reports.personal import personalReport, projectTasksReport
from pao.reports.project import projectManagerReport, projectBudgetReport, projectIntensityReport
from pao.reports.department import departmentManagerReport, departmentProjectsReport, departmentBudgetReport, departmentLoadReport
from pao.reports.enterprise import enterpriseManagerReport, enterpriseProjectsReport, enterpriseBudgetReport, enterpriseEmployeeLoadReport, enterpriseUnexecutedProjectsReport
from pao.menu.lists import managedProjectsList, departmentEmployeeList, employeeList, enterpriseEmployeeList
from pao.menu.buildPath import buildPath
from pao.helpers import *
from pao.forms import UploadFileForm

from django.shortcuts import render_to_response
import datetime
from django.contrib.auth.views import login, logout
from django.contrib.auth.decorators import login_required

def infoPackage(request):
    info = {}
    defaultInterval = datetime.timedelta(days=365)
    info['groups'] = getUserGroups(request.user)
    info['username'] = request.user.username
    info['departmentId'] = request.user.employee.department.id
    info['pathList'] = buildPath(request, info['groups'])
    info['path'] = request.path
    info['yearList'] = generateYears()
    if not request.session.has_key('startDate') or not request.session.has_key('endDate'):
        request.session['startDate'] = datetime.date.today() - defaultInterval
        request.session['endDate'] =datetime.date.today()
    if request.session['startDate'] == None:
        info['startDate'] = '-'
    else:
        info['startDate'] = request.session['startDate'].strftime('%Y-%m')
    if request.session['endDate'] == None:
        info['endDate'] = '-'
    else:
        info['endDate'] = request.session['endDate'].strftime('%Y-%m')
    request.session['lastPath'] = request.path
    return info

@login_required
def viewPersonalReport(request, employee):
    if not hasPermissions(request.user, 'Personal', employee):
        return render_to_response('no_access.html')
    report = personalReport(employee)
    params = {'reports': report, 'employee': employee}
    params.update(infoPackage(request))
    return render_to_response('reports/personalReport.html', params)

@login_required
def viewProjectTasksReport(request, employee, project):
    if not hasPermissions(request.user, 'Personal', employee):
        return render_to_response('no_access.html')
    report = projectTasksReport(employee, project)
    params = {'project': report}
    params.update(infoPackage(request))
    return render_to_response('reports/projectTasksReport.html', params)

@login_required
def viewProjectListReport(request, employee):
    if not hasPermissions(request.user, 'Personal', employee):
        return render_to_response('no_access.html')
    report = managedProjectsList(employee)
    params = {'report': report}
    params.update(infoPackage(request))
    return render_to_response('reports/projectListReport.html', params)

@login_required
def viewProjectManagerReport(request, project):
    if not hasPermissions(request.user, 'Project', project):
        return render_to_response('no_access.html')
    report = projectManagerReport(project) 
    params = {'project': report}
    params.update(infoPackage(request))
    #pathList = buildPath(request.path+','+project['manager'], request.user.employee.department.id, request.user.username, groups)
    return render_to_response('reports/projectManagerReport.html', params)

@login_required
def viewProjectIntensityReport(request, projectId, start=None, end=None):
    if not hasPermissions(request.user, 'Project', projectId):
        return render_to_response('no_access.html')
    start, end = parseDateFromString(start), parseDateFromString(end)
    rememberDates(request, start, end)
    report = projectIntensityReport(projectId, start, end)
    chart = intensityChart(report)
    params = {'project': report, 'image': chart}
    params.update(infoPackage(request))
    #projectManager = projectManagerReport(projectId)
    #pathList = buildPath(request.path+',' + projectManager['manager'], request.user.employee.department.id, request.user.username, groups)
    return render_to_response('reports/projectIntensityReport.html', params)

@login_required
def viewProjectBudgetReport(request, project, start=None, end=None):
    if not hasPermissions(request.user, 'Project', project):
        return render_to_response('no_access.html')
    start, end = parseDateFromString(start), parseDateFromString(end)
    rememberDates(request, start, end)
    report = projectBudgetReport(project, start, end)
    chart = budgetChart(report)
    params = {'project': report, 'image': chart}
    params.update(infoPackage(request))
    #projectManager = projectManagerReport(project)
    #pathList = buildPath(request.path+','+projectManager['manager'], request.user.employee.department.id, request.user.username, groups)
    return render_to_response('reports/projectBudgetReport.html', params)

@login_required
def viewDepartmentManagerReport(request, department, start=None, end=None):
    if not hasPermissions(request.user, 'Department', department):
        return render_to_response('no_access.html')
    start, end = parseDateFromString(start), parseDateFromString(end)
    rememberDates(request, start, end)
    report = departmentManagerReport(department, start, end)
    params = {'department': report}
    params.update(infoPackage(request))
    return render_to_response('reports/departmentManagerReport.html', params) 

@login_required
def viewDepartmentProjectsReport(request, department, start=None, end=None):
    if not hasPermissions(request.user, 'Department', department):
        return render_to_response('no_access.html')
    start, end = parseDateFromString(start), parseDateFromString(end)
    rememberDates(request, start, end)
    report = departmentProjectsReport(department, start, end)
    params = {'project': report}
    params.update(infoPackage(request))
    return render_to_response('reports/departmentProjectsReport.html', params)

@login_required
def viewDepartmentBudgetReport(request, department, start=None, end=None):
    if not hasPermissions(request.user, 'Department', department):
        return render_to_response('no_access.html')
    start, end = parseDateFromString(start), parseDateFromString(end)
    rememberDates(request, start, end)
    report = departmentBudgetReport(department, start, end)
    chart = budgetChart(report)
    params = {'department': report, 'image': chart}
    params.update(infoPackage(request))
    return render_to_response('reports/departmentBudgetReport.html', params)

@login_required
def viewDepartmentLoadReport(request, department, start=None, end=None):
    if not hasPermissions(request.user, 'Department'):
        return render_to_response('no_access.html')
    start, end = parseDateFromString(start), parseDateFromString(end)
    rememberDates(request, start, end)
    report = departmentLoadReport(start, end)
    params = {'report': report}
    params.update(infoPackage(request))
    #chart = loadChart(report)
    return render_to_response('reports/departmentLoadReport.html', params)


@login_required
def viewDepartmentEmployeeReport(request, department):
    if not hasPermissions(request.user, 'Department', department):
        return render_to_response('no_access.html')
    report = departmentEmployeeList(department)
    params = {'report': report}
    params.update(infoPackage(request))
    return render_to_response('reports/departmentEmployeeReport.html', params)

@login_required
def viewEnterpriseManagerReport(request, start=None, end=None):
    if not hasPermissions(request.user, 'Enterprise'):
        return render_to_response('no_access.html')
    start, end = parseDateFromString(start), parseDateFromString(end)
    rememberDates(request, start, end)
    report = enterpriseManagerReport(start, end)
    params = {'department': report}
    params.update(infoPackage(request))
    return render_to_response('reports/enterpriseManagerReport.html', params)

@login_required
def viewEnterpriseUnexecutedReport(request):
    if not hasPermissions(request.user, 'Enterprise'):
        return render_to_response('no_access.html')
    report = enterpriseUnexecutedProjectsReport()
    params = {'project': report}
    params.update(infoPackage(request))
    return render_to_response('reports/enterpriseUnexecutedProjectsReport.html', params)

@login_required
def viewEnterpriseProjectsReport(request, start=None, end=None):
    if not hasPermissions(request.user, 'Enterprise'):
        return render_to_response('no_access.html')
    start, end = parseDateFromString(start), parseDateFromString(end)
    rememberDates(request, start, end)
    report = enterpriseProjectsReport(start, end)
    params = {'project': report}
    params.update(infoPackage(request))
    return render_to_response('reports/enterpriseProjectsReport.html', params)
    
@login_required
def viewEnterpriseBudgetReport(request, start=None, end=None):
    if not hasPermissions(request.user, 'Enterprise'):
        return render_to_response('no_access.html')
    start, end = parseDateFromString(start), parseDateFromString(end)
    rememberDates(request, start, end)
    report = enterpriseBudgetReport(start, end)
    chart = budgetChart(report)
    params = {'department': report, 'image': chart}
    params.update(infoPackage(request))
    return render_to_response('reports/enterpriseBudgetReport.html', params)


@login_required
def viewEnterpriseEmployeeReport(request):
    if not hasPermissions(request.user, 'Enterprise'):
        return render_to_response('no_access.html')
    report = enterpriseEmployeeList()
    params = {'report': report}
    params.update(infoPackage(request))
    return render_to_response('reports/enterpriseEmployeeReport.html', params)


@login_required
def viewEnterpriseLoadReport(request, start=None, end=None):
    if not hasPermissions(request.user, 'Enterprise'):
        return render_to_response('no_access.html')
    start, end = parseDateFromString(start), parseDateFromString(end)
    rememberDates(request, start, end)
    report = enterpriseEmployeeLoadReport(start, end)
    chart = loadChart(report)
    params = {'report': report, 'image': chart}
    params.update(infoPackage(request))
    return render_to_response('reports/enterpriseLoadReport.html', params)

@login_required
def index(request):
    groups = getUserGroups(request.user)
    defaultInterval = datetime.timedelta(days=365)
    start = (datetime.date.today() - defaultInterval).strftime('%Y-%m')
    end = datetime.date.today().strftime('%Y-%m')
    if 'Admin' in groups:
        return HttpResponseRedirect('/admin')
    elif 'Enterprise' in groups:
        return HttpResponseRedirect('/enterprise/manager/' + start + '/' + end)
    elif 'DepartmentManager' in groups:
        return HttpResponseRedirect('/department/manager/'+str(request.user.employee.department.id)+'/'+start + '/' + end)
    elif 'ProjectManager' in groups:
        return HttpResponseRedirect('/project/list/'+request.user.username)
    else: #Employee
        return HttpResponseRedirect('/personal/'+request.user.username)

@login_required
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            #try:
            DataLoader(request.FILES['file']).updateDatabase()
            #except:
            #    return HttpResponseRedirect(reverse(uploadError))
            return HttpResponseRedirect(reverse(uploadSuccess))
    else:
        form = UploadFileForm()
    return render_to_response('admin/upload.html', {'form': form})

@login_required
def uploadSuccess(request):
    return render_to_response('admin/upload_success.html')

@login_required
def uploadError(request):
    return render_to_response('admin/upload_error.html')
